package org.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 不依赖于 Spring 的 ActiveMq 工具类。
 * 从其他人的demo项目中抽取，不一定符合实际项目需求。
 *
 * @author 别人
 */
@Slf4j
public class ActiveMqUtils {

    public final String BROKER_URL = "tcp://localhost:61616";

    public final String PASSWORD = null;

    public final String USERNAME = null;

    public ConnectionFactory connectionFactory = null;

    public Connection connection = null;

    public Session session = null;

    public Destination destination = null;

    public MessageProducer messageProducer = null;

    public TextMessage textMessage = null;

    public synchronized boolean convertAndSend(String topicName, String info) {
        try {
            try {
                if (null == connectionFactory || null == messageProducer || null == session) {
                    connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_URL);
                    connection = connectionFactory.createConnection();
                    connection.start();
                    session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
                    destination = session.createTopic(topicName); // 设置模式 Topic
                    messageProducer = session.createProducer(destination); // 创建主题
                    textMessage = session.createTextMessage();
                }
                textMessage.setText(info);
                messageProducer.send(destination, textMessage);
                session.commit();
            } catch (Exception e) {
                if (null != messageProducer) {
                    try {
                        messageProducer.close();
                    } catch (Exception e2) {
                    }
                }
                if (null != session) {
                    try {
                        session.close();
                    } catch (Exception e2) {
                    }
                }
                if (null != connection) {
                    try {
                        connection.close();
                    } catch (Exception e2) {
                    }
                }
                connectionFactory = null;
                e.printStackTrace();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
